import React, { Component } from 'react';
import { NavBar, Toast } from 'antd-mobile'
import { user_register } from '../api/login'
// 导入scss
import '../styles/Login.scss'

class Login extends Component {
    constructor(props) {
        super(props);
        this.state = { phone: '', pass: '', conpass: '' }
    }

    // 点击返回
    back() {
        this.props.history.goBack();
    }

    //更改表单变为授控组件
    handleChange(e) {
        this.setState({
            [e.target.name]: e.target.type == 'checkbox' ? e.target.checked : e.target.value
        })
    }

    // 点击注册时触发
    Register() {
        if (this.state.phone == '') {
            Toast.show({
                content: '请输入手机号',
            })
        }
        else if (this.state.pass == '') {
            Toast.show({
                content: '请输入密码',
            })
        }
        else if (this.state.conpass == '') {
            Toast.show({
                content: '请再次确认密码',
            })
        }
        //   先进行判断手机号是否符合正则
        else if (/^1[3456789]\d{9}$/.test(this.state.phone)) {
            // 手机号合适后即可发送请求
            user_register({ phone: this.state.phone, pass: this.state.pass }).then((res) => {
                if (res.data.code == 400) {
                    Toast.show({
                        content: '该手机号已被注册',
                    })
                }
                else if (res.data.code == 200) {
                    Toast.show({
                        content: '注册成功',
                    })
                    this.props.history.push({ pathname: '/login' })
                }

            })
        } else {
            Toast.show({
                content: '手机号有误',
            })
        }
    }

    render() {
        return (
            <div className='login'>
                <NavBar onBack={() => { this.back() }}> <h4>注册页</h4> </NavBar>
                <div className='login-one'>
                    <div className='block'>
                        <input type="text" name='phone' value={this.state.phone} onChange={(e) => { this.handleChange(e) }} placeholder='请输入手机号' />
                    </div>
                    <div className='block'>
                        <input type="text" name='pass' value={this.state.pass} onChange={(e) => { this.handleChange(e) }} placeholder='请输入密码' />
                    </div>
                    <div className='block'>
                        <input type="text" name='conpass' value={this.state.conpass} onChange={(e) => { this.handleChange(e) }} placeholder=' 再次确认密码' />
                    </div>
                    <div className='block'>
                        <input className='btn' type="button" value='注册' onClick={() => { this.Register() }} />
                    </div>
                </div>
            </div>
        );
    }
}

export default Login;